(function(){
    angular.module('app').controller("agNewOrderCtrl",function($scope, proxy, $stateParams){
        // =========================================== 公用 ==============================================
        var areaType = "";
        $scope.advRights = !(localStorage.advRights != "0" && $stateParams.type == 0);
        $scope.isDirect = isDirect;//判断是否直客
        $scope.accountType = $stateParams.type;//判断是否是广告主登录
        $scope.oType = $stateParams.oType;
        $scope.permission = PERMISSION;
        var flag;//判断是否是第一次进入第二步
        var date= new Date(), st, et;
        $scope.nextText = "下一步";
        //新建
        $scope.activeTitle = "请选择活动";
        if ($stateParams.activeId != "") {
            $scope.activeId = $stateParams.activeId;
            $scope.materialList = []
            getActiveInfo($scope, proxy);
        }
        // 判断是否有溢价设置
        if($scope.accountType != '0' && $scope.isDirect != '1') {
            getPremiumMax(proxy,$scope);
        }
        $scope.orderId = $stateParams.orderId;
        $scope.data = {
            //step1
            "orgID": agencyID,
            "advertiserID": $stateParams.id,
            "activityID": $stateParams.activeId,
            "name": "",
            "creativeID": [],
            "orderBudget": "",
            "frequencyLimit": "",
            "frequencyUnit": "day",
            "startTime": date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate(),
            "endTime": date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate(),
            "type": $stateParams.oType=='1'?'rtb':'pdb',
            "controlMode": "0",
            "speedUnit": "day",
            "limitPrice": "",
            "speedUp": "1",
            //step2
            "direct": {
                pkgType: '0'
            },
            //step4
            "profit": "",
            "bidPrice": "",
            "chargeMode": "cpm"
        };
        //判断交易类型
        if ($stateParams.oType == '1') {
            $scope.orderType = 'bid';
            $scope.data.interactionType = "1";
            $scope.data.platform = "ios";
        } else {
            $scope.orderType = 'deal';
            $scope.data.platform = "ios";
            $scope.data.interactionType = "1";
            $scope.data.SKU = [];
        }
        //判断第几步
        //$scope.step = sessionStorage.step || 1;
        $scope.step = 1;
        //下一步
        $scope.next = function (step) {
            console.log($scope.app_num)
            var err = inputCheck($scope);
            if (err) {
                layer.msg(err);
                return;
            }
            if ($scope.step < 4) {
                $scope.nextText = "下一步";
            }
            if ($scope.step == 1 || step >= 2) {
                $scope.data.endTime = $scope.endTime ? "NULL" : $scope.data.endTime;
                var frequencyLimit = $scope.data.frequencyLimit;
                if( frequencyLimit != '' && (isNaN(frequencyLimit) || frequencyLimit < 0) ) {
                    return layer.msg("频次必须为大于0的数字！")
                }
                if ($scope.data.controlMode == "1") {
                    $scope.data.limitPrice = "";
                } else {
                    $scope.data.limitView = "";
                }
                if ($stateParams.oType == '2') {
                    skuList();
                } else {
                    getPublishMeidaType($scope,proxy);
                    //小时定向
                    $scope.data.direct.deliverTimeIn = $scope.checkArr.join(',')
                    if ($scope.orderId != "") {
                        //设备品牌
                        if ($scope.data.direct.phoneBrandIn != "") {
                            $scope.position.deBrand = "custom";
                            $scope.position.deBrandOutIn = "in";
                            editTree($scope, "brand", $scope.data.direct.phoneBrandIn);
                        } else if ($scope.data.direct.phoneBrandOut != "") {
                            $scope.position.deBrand = "custom";
                            $scope.position.deBrandOutIn = "in";
                            editTree($scope, "brand", $scope.data.direct.phoneBrandIn);
                        }

                        //设备版本
                        if ($scope.data.direct.osVersionIn != "") {
                            $scope.position.deVersion = "custom";
                            $scope.position.deVersionOutIn = "in";
                            editTree($scope, "version", $scope.data.direct.osVersionIn);
                        } else if ($scope.data.direct.osVersionOut != "") {
                            $scope.position.deVersion = "custom";
                            $scope.position.deVersionOutIn = "in";
                            editTree($scope, "version", $scope.data.direct.osVersionOut);
                        }

                        $scope.depotFilter.depotType = $scope.data.direct.depotType || ($scope.data.platform == 'ios'?'IDFA':'IMEI')
                        // ID定向
                        if($scope.data.direct.depotIDs != '') {
                            $scope.bidActive = '2'
                            $scope.depotCheck = $scope.data.direct.depotIDs.split(",")
                            // 此数组用于判断已勾选并且状态不为已上线
                            $scope.tempDepot = $scope.data.direct.depotIDs.split(",")
                            $scope.getDepotList(true);
                        } else {
                            $scope.depotFilter.depotType = $scope.data.platform == 'ios'?'IDFA':'IMEI'
                            $scope.getDepotList();
                            $scope.bidActive = '1'
                        }
                        getPublish($scope, proxy, 'edit');
                        getMedia($scope, proxy, 'edit');
                        getNewMeida($scope, proxy, 'edit')
                        if($scope.data.direct.spaceIDIn != "" && $scope.data.direct.pkgType == '0'){ // 广告位定向恢复
                        // if($scope.data.direct.spaceIDIn != ""){ // 广告位定向恢复
                            $scope.position.publish = "space";
                            $scope.position.spaceOutIn = "in";
                            editTree($scope, "space", $scope.data.direct.spaceIDIn);
                        } else if ($scope.data.direct.spaceIDOut != "" && $scope.data.direct.pkgType == '0') {
                        // } else if ($scope.data.direct.spaceIDOut != "") {
                            $scope.position.publish = "space";
                            $scope.position.spaceOutIn = "out";
                            editTree($scope, "space", $scope.data.direct.spaceIDOut);
                        }

                        //设备品牌
                        if ($scope.data.direct.phoneBrandIn != "") {
                            $scope.position.deBrand = "custom";
                            $scope.position.deBrandOutIn = "in";
                            editTree($scope, "brand", $scope.data.direct.phoneBrandIn);
                        } else if ($scope.data.direct.phoneBrandOut != "") {
                            $scope.position.deBrand = "custom";
                            $scope.position.deBrandOutIn = "in";
                            editTree($scope, "brand", $scope.data.direct.phoneBrandIn);
                        }

                        //设备版本
                        if ($scope.data.direct.osVersionIn != "") {
                            $scope.position.deVersion = "custom";
                            $scope.position.deVersionOutIn = "in";
                            editTree($scope, "version", $scope.data.direct.osVersionIn);
                        } else if ($scope.data.direct.osVersionOut != "") {
                            $scope.position.deVersion = "custom";
                            $scope.position.deVersionOutIn = "in";
                            editTree($scope, "version", $scope.data.direct.osVersionOut);
                        }
                    } else {
                        getPublish($scope, proxy);
                        getMedia($scope, proxy);
                        getNewMeida($scope, proxy)
                        getBrand($scope, proxy);
                        getOsVersion($scope, proxy);
                        getSpace($scope, proxy);

                        // ID定向
                        $scope.depotFilter.depotType = $scope.data.platform == 'ios'?'IDFA':'IMEI'
                        $scope.getDepotList();
                    }
                    //获取行业包
                    industryList($scope, proxy)
                    // 获取人群包
                    crowdList($scope, proxy)
                }
                if ($scope.limit) {
                    $scope.data.orderBudget = "0";
                }
            }
            if ($scope.step == 2 || step >= 3) {
                if ($stateParams.oType == '1') {
                    $scope.data.direct.ageIn = $scope.position.age == "all" ? "" : $scope.position.ages.join(",");
                    $scope.data.direct.earningIn =  $scope.position.income == "all" ? "" : $scope.position.incomes.join(",");
                    $scope.data.direct.genderIn = $scope.position.people == "all" ? "":$scope.position.sex;
                    $scope.data.direct.depotIDs = $scope.depotCheck.join(",");
                    $scope.data.direct.depotType = $scope.depotFilter.depotType;
                    $scope.data.direct.sourceIn = $scope.position.publish=="all" ? $scope.publishConfig.selectArr.join(",") : "";
                    $scope.data.direct.optimizeApp = $scope.position.publish=="select" ? $scope.mediaConfig.selectArr.join(",") : "";
                    $scope.data.direct.newApp = $scope.position.publish=="new" ? $scope.newMediaConfig.selectArr.join(",") : "";
                    $scope.data.direct.devicePrice = $scope.position.dePrice=="all" ? "" : $scope.position.dePrices.join(",");
                    //$scope.data.direct.userLocationIn = $scope.position.area=="all" ? $scope.publishConfig.selectArr.join(",") : "";
                    $scope.data.direct.ISP = $scope.position.ISP!="all" ? $scope.position.ISPs.join(",") : "";
                    $scope.data.direct.net = $scope.position.net!="all" ? $scope.position.nets.join(",") : "";
                    //广告位定向
                    if ($scope.position.publish == "space" && $scope.position.spaceOutIn == "in") {
                        $scope.data.direct.spaceIDIn = $scope.position.spaceIds.join();
                        $scope.data.direct.spaceIDOut = "";
                    } else if ($scope.position.publish == "space" && $scope.position.spaceOutIn == "out") {
                        $scope.data.direct.spaceIDOut = $scope.position.spaceIds.join();
                        $scope.data.direct.spaceIDIn = "";
                    // } else if($scope.position.publish == "all") {
                    //     $scope.data.direct.spaceIDOut = $scope.position.spaceIds.join();
                    //     $scope.data.direct.spaceIDIn = $scope.data.direct.osVersionIn = "";
                    // }
                    } else if($scope.position.publish != "space"){
                        $scope.data.direct.spaceIDOut = $scope.data.direct.spaceIDIn = "";
                    }
                    // 选择包
                    if ($scope.position.publish == "industry") {
                        $scope.data.direct.pkgType = '1'
                        $scope.data.direct.pkgID = $scope.industryPkgId
                    } else if ($scope.position.publish == "crowd") {
                        $scope.data.direct.pkgType = '2'
                        $scope.data.direct.pkgID = $scope.crowdPkgId
                    } else {
                        $scope.data.direct.pkgType = '0'
                    }
                    //设备型号定向
                    if ($scope.position.deBrand != "all" && $scope.position.deBrandOutIn == "in") {
                        $scope.data.direct.phoneBrandIn = $scope.position.brandIds.join(":");
                        $scope.data.direct.phoneBrandOut = "";
                    } else if ($scope.position.deBrand != "all" && $scope.position.deBrandOutIn == "out") {
                        $scope.data.direct.phoneBrandOut = $scope.position.brandIds.join(":");
                        $scope.data.direct.phoneBrandIn = "";
                    } else if($scope.position.deBrand == "all") {
                        $scope.data.direct.phoneBrandIn = $scope.data.direct.phoneBrandOut = "";
                    }
                    //设备版本定向
                    if ($scope.position.deVersion != "all" && $scope.position.deVersionOutIn == "in") {
                        $scope.data.direct.osVersionIn = $scope.position.versionIds.join(",");
                        $scope.data.direct.osVersionOut = "";
                    } else if ($scope.position.deVersion != "all" && $scope.position.deVersionOutIn == "out") {
                        $scope.data.direct.osVersionOut = $scope.position.versionIds.join(",");
                        $scope.data.direct.osVersionIn = "";
                    } else if($scope.position.deVersion == "all") {
                        $scope.data.direct.osVersionOut = $scope.data.direct.osVersionIn = "";
                    }

                    if($scope.position.area != "all") {
                        var tempArr = [];
                        $scope.data.direct.locationType = $scope.position.area == "location"?"2":"1"; // 2省市 1一二线城市
                        $("#areaCustom .selected-item").each(function(){
                            tempArr.push($(this).attr("id"))
                        })
                        $scope.data.direct.userLocationIn = tempArr.join(",")
                    } else {
                        $scope.data.direct.userLocationIn = "";
                        $scope.data.direct.locationType = "0"
                    }

                    if($scope.position.publish == 'type') {
                        var appTypeArr = [];
                        $("#typeCustom .selected-item").each(function () {
                            appTypeArr.push($(this).attr("id"))
                        })
                        if ($scope.typeInOut == "in") {
                            $scope.data.direct.appTypeIn = appTypeArr.join(",");
                            $scope.data.direct.appTypeOut = "";
                        } else {
                            $scope.data.direct.appTypeIn = "";
                            $scope.data.direct.appTypeOut = appTypeArr.join(",");
                        }
                    } else {
                        $scope.data.direct.appTypeIn = "";
                        $scope.data.direct.appTypeOut = "";
                    }
                } else {
                    for (var i = 0; i < $scope.data.SKU.length; i++) {
                        buySkuInfo.adxDealIDs.push($scope.data.SKU[i].adxDealID);
                        buySkuInfo.adxIDs.push($scope.data.SKU[i].adxID);
                        var spaces = $scope.data.SKU[i].spaceInfo;
                        for (var j = 0; j < spaces.length; j++) {
                            buySkuInfo.adxSpaceIDs.push(spaces[j].spaceID);
                        }
                    }
                }
                if ($stateParams.orderId != "") {
                    getOrderCreative($scope, proxy, $stateParams.orderId);
                }
            }
            if ($scope.step == 3 || step == 4) {
                if ($scope.data.interactionType == '2') {
                    $scope.data.singleApp = $scope.app_num == 'one' ? 'true' : 'false'
                }
                $scope.nextText = "完成";
                if (step && step != 4) {
                    $scope.nextText = "下一步";
                }
                $scope.dataView = {
                    "activeName": $scope.activeTitle,
                    "orderBudget": $scope.data.orderBudget == "0" || $scope.data.orderBudget == ""? "无预算限制" : $scope.data.orderBudget,
                    "frequencyUnit": $scope.data.frequencyUnit == "day" ? "天":"小时",
                    "time": $scope.endTime ? "长期投放" : $scope.data.startTime + "至" + $scope.data.endTime,
                };
                if ($scope.orderId == '') {
                    getProfit($scope, proxy);
                }
                if ($stateParams.oType == '1') {
                    $scope.dataView.sex =  $scope.data.direct.genderIn == "" ? "不限":$scope.data.direct.genderIn=="m"?"男":"女";
                    $scope.dataView.controlMode = $scope.data.controlMode == "0"?"按花费控制：":"按展示量控制：";
                    if ($scope.data.direct.earningIn == "") {
                        $scope.dataView.income = "不限";
                    } else {
                        var incomes = $scope.data.direct.earningIn.split(","),
                            incomeName = ["1000RMB以下", "1001-3000RMB", "3001-5000RMB", "5001-10000RMB", "10000RMB以上"],
                            titleArr = [];
                        for (var i = 0; i < incomes.length; i++) {
                            titleArr.push(incomeName[incomes[i] - 1]);
                        }
                        $scope.dataView.income = titleArr.join(",");
                    }
                    if ($scope.data.direct.ageIn == "") {
                        $scope.dataView.age = "不限";
                    } else {
                        var ages = $scope.data.direct.ageIn.split(","),
                            ageName = ["18岁以下", "18岁至24岁", "25岁至34岁", "35岁以上"],
                            titleArr = [];
                        for (var i = 0; i < ages.length; i++) {
                            titleArr.push(ageName[ages[i] - 1]);
                        }
                        $scope.dataView.age = titleArr.join(",");
                    }
                }
            }
            if ($scope.step == 4 && !step) {
                var bidMax = $scope[$scope.data.chargeMode+"Max"];
                var direct = $scope.data.direct;
                if($scope.data.bidPrice > bidMax) return layer.msg("订单出价不能超过"+bidMax+"元")
                if($scope.data.profit < 0) return layer.msg("利润必须大于等于0！")
                if($scope.data.profit > $scope.premiumMax*100) return layer.msg("利润设置不能超过"+($scope.premiumMax*100)+"%")
                
                // 哪些用户可以看到广告
                if($scope.bidActive == 1) {
                    // 清空用户ID定向
                    direct.depotIDs = "";
                    direct.depotType = "";
                } else {
                    // 清空人口属性
                    direct.genderIn = direct.earningIn = direct.ageIn = '';
                }
                if($stateParams.orderId == "") {
                    if ($scope.profit == "false") {
                        $scope.data.profit = ""
                    } else {
                        $scope.data.profit = ($scope.data.profit / 100) + "";
                    }
                    if ($scope.data.startTime.indexOf("00:00") == -1) {
                        $scope.data.startTime += " 00:00:00";
                        if (!$scope.endTime && $scope.data.endTime.replace(/\s/g, "") != "") {
                            $scope.data.endTime += " 23:59:59";
                        } else {
                            $scope.endTime = "NULL";
                        }
                    }
                    proxy.proxy({
                        url: STATIC_URL.domian+'/dsp/order/add',
                        data: {
                            "data": $scope.data
                        },
                        load: true,
                        success: function(res){
                            if (res.status == 0) {
                                window.location.href="#/agent/"+ $scope.accountType +"/"+ $stateParams.id +"/delivery/order";
                            }
                        }
                    });
                } else {
                    orderEdit($scope, proxy, $stateParams.id);
                }
            }
            if (step) {
                $scope.step = step;
            } else if ($scope.step != 4){
                $scope.step++;
            }
            console.log($scope.data);
        };
        //上一步
        $scope.previous = function () {
            $scope.step--;
            if ($scope.step == 1) {
                $scope.data.endTime = $scope.data.endTime == "NULL" ? "" : $scope.data.endTime;
            }
            if($scope.step == 2 && $stateParams.oType == '2' ) {
                // 解决当页面切换至第合约二步时瀑布流样式错乱
                setTimeout(function () {
                    $('.grid').masonry(masOption);
                },300)
            }
            $scope.nextText = "下一步";
        };
        //跳转
        $scope.stepJump = function (step) {
            inputCheck($scope);
            if (step == 4) {
                $scope.nextText = "完成";
            } else {
                $scope.nextText = "下一步";
            }
            $scope.next(step);
        };
        //取消
        $scope.cancel = function () {
            window.location.href = "#/agent/"+ $scope.accountType +"/"+ $stateParams.id +"/delivery/order";
        };

        $scope.load = function () {
            if (!$scope.activeId || $scope.activeId=='') {
                chooseTime($scope);
            }
        };
        var i = 0;
        $scope.clearTree1 = function (type) {
            $scope.position.spaceNames = [];
            $scope.spaceTree.checkAllNodes(false);
        }
        $scope.clearTree2 = function () {
            $(".custom-box .check.checked").removeClass("checked");
            $(".custom-box .selected-item").remove();
        }
        $scope.clearTree3 = function () {
            $scope.position.brandNames = [];
            $scope.brandTree.checkAllNodes(false);
        }
        $scope.clearTree4 = function () {
            $scope.position.versionNames = [];
            $scope.versionTree.checkAllNodes(false);
        }
        //==========================================  step 1  =========================================
        $scope.speed = "加速";
        $scope.sUnit = "天";
        $scope.tUnit = "天";
        $scope.limit = true; //控制预算是否可输入
        $scope.endTime = true; //是否长期投放
        // 判断是否推广多个APP
        $scope.app_num = 'one'

        //存储小时投放时间
        $scope.checkArr = [];

        $scope.orderBudget = function () {
            $scope.limit = !$scope.limit;
        };
        //不能输入小数点
        $scope.filterNum = function () {
            var ss=window.event||e;
            if(ss.keyCode == 110 || ss.keyCode == 190){
                ss.preventDefault();
            }
        };
        //是否加速
        $scope.isSpeed = function (item) {
            $scope.data.speedUp = item.id;
        };
        //改变加速单位
        $scope.speedUnit = function (item) {
            $scope.data.speedUnit = item.val;
        };
        //单选框
        $scope.behavior = "page";
        //下拉框
        $scope.rateDrop = [{"id": "0", "name": "匀速"}, {"id": "1", "name": "加速"}];
        $scope.timeUnit = [{"id": "1", "name": "小时", "val": "hour"},{"id": "2", "name": "天", "val": "day"}];
        //获取活动列表
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/activity/list',
            data: {
                "size": "-1",
                "sort": ["cTime,1"]
            },
            load: true,
            success: function(res){
                $scope.activeList = res.data.data;
            }
        });
        // 获得价格最大值
        getPriceMax(proxy, $scope)
        //选择活动
        $scope.selectActive = function (active) {
            $scope.data.activityID = active.activityID;
            $scope.activeTitle = active.name;
            $scope.activeId = active.activityID;
            $scope.materialList = active.materialList = active.materialList || [] ;
            $scope.data.creativeID = active.creativeID = active.creativeID || [];
            $scope.activeIndustry = active.industry;
            getActiveInfo($scope, proxy);
        };
        //频次单位
        $scope.frequencyUnit = function (unit) {
            $scope.data.frequencyUnit = unit.val;
        };

        // 监测
        $scope.monitorTitle = '请选择一个检测站点';
        $scope.convertCheck = [];
        $scope.selectSite = function(item) {
            $scope.convertCheck = [];
            $scope.convertList = item.events || [];
            $scope.data.monitorSite = item.id;
            $scope.data.monitorConvert = "";
        }
        $scope.selectconvert = function(convertCheck) {
            var convertList = [],ids = [];
            convertCheck.forEach(function(v) {
                var item = JSON.parse(v);
                convertList.push(item)
                ids.push(item.id);
            })
            $scope.convertCheckList = convertList;
            $scope.data.monitorConvert = ids.join(",")
        }
        $scope.removeCover = function(index) {
            $scope.convertCheckList.splice(index,1);
            $scope.convertCheck.splice(index,1);
        }



        //==========================================  竞价step 2  ==========================================
        hasIP(proxy,$scope);
        $scope.spaceInOut = 'in';
        // $scope.oTypeInOut = 'in';
        $scope.typeInOut = 'in';
        $scope.bidActive = '1';
        // ID库
        $scope.depotFilter = {
            depotType: '',
            name: '',
            // online: $scope.orderId? '10,30':"30",
            state: '10'
        }
        $scope.onlineEnum = {
            10: '离线',
            20: '上线中',
            30: '已上线',
            40: '离线中',
            50: '上传中',
            60: '未完成',
            100: '出错，联系管理员'
        }
        $scope.depotReset = function() {
            $scope.depotFilter.name = '';
            $scope.getDepotList();
        }
        $scope.depotCheck = [];
        $scope.tempDepot = [];
        $scope.depotList = [];
        $scope.changeDepot = function(item) {
            $scope.depotFilter.depotType = item;
            $scope.getDepotList()
        }
        // depotIDs
        $scope.getDepotList = function (flag) {
            proxy.proxy({
                url: STATIC_URL.domian + '/dsp/device/depot/owner/list',
                data: {
                    filter: $scope.depotFilter,
                    page: '1',
                    size: '9999'
                },
                success: function(res) {
                    $scope.depotList = res.data.data || [];
                    if(flag !== true) {
                        $scope.depotCheck = [];
                    } else {
                        // 清除非已上线的id,防止无法取消勾选
                        $scope.depotList.forEach(function(item) {
                            var index = $scope.depotCheck.indexOf(item.id);
                            if(index != -1 && item.online != '30') {
                                $scope.depotCheck.splice(index,1)
                            }
                        })
                        console.log($scope.depotCheck)
                    }
                }
            })
        }

        $scope.pkgSpaceIds = ''

        $scope.newAppTips = function () {
            layer.tips('包含近一个月对接的新媒体', '.newAppTips', {
              tips: [1, '#d8d58d']
            });
        }
        // 选择行业包
        $scope.industrySelectPkg = function (val) {
            $scope.industryPkgId = val
        }
        // 选择人群包
        $scope.crowdSelectPkg = function (val) {
            $scope.crowdPkgId = val
        }
        //定向控制
        $scope.position = {
            people: "all",
            sex: "m",
            age: "all",
            ages: [],
            ip: "all",
            ips: "",
            income: "all",
            incomes: [],
            area: "all",
            publish: "all",
            mSystem: "all",
            net: "all",
            nets: [],
            ISP: "all",
            ISPs: [],
            dePrice: "all",
            dePrices: [],
            deBrand: "all",
            deBrandOutIn: "in",
            brandIds:[],
            brandNames: [],
            deVersion: "all",
            deVersionOutIn: "in",
            versionIds:[],
            versionNames: [],
            spaceOutIn: "in",
            spaceNames: [],
            spaceIds: [],
            searchSpace: ''
        };

        //定向添加事件
        $scope.add = function (type, key) {
            $scope.position[type + "Ids"] = [];
            $scope.position[type + "Names"] = [];
            var nodes = $scope[type + "Tree"].getCheckedNodes();
            for (var i = 0, l = nodes.length; i < l; i++) {
                if (!nodes[i].isParent) {
                    if (type == 'brand') {
                        $scope.position[type + "Ids"].push(nodes[i].name);
                    } else {
                        $scope.position[type + "Ids"].push(nodes[i].id);
                    }
                    $scope.position[type + "Names"].push(nodes[i][key]);
                }
            }
        };
        // 广告位keyup事件
        $scope.keupSearch = function(e) {
            if(e.keyCode == 13) {
                $scope.spaceSearch();
            }
        }

        //广告位搜索
        $scope.spaceSearch = function () {
            var nodes = $scope.spaceTree.getNodesByParamFuzzy('name', $scope.position.searchSpace)
            $scope.spaceTree.selectNode(nodes[0]);
            $scope.position.searchSpace = ''
        }

        $scope.publishChange = function (val) {
            if (val === 'select') {
                $scope.mediaName = ['']
            } else if(val === 'newMedia') {
                $scope.newMediaName = ['']
            }

            $scope.data.direct.sourceIn = ''
            $scope.data.direct.appTypeIn = ''
            $scope.data.direct.appTypeOut = ''
            $scope.data.direct.newApp = ''
            $scope.data.direct.optimizeApp = ''
            $scope.data.direct.pkgType = ''
            $scope.data.direct.spaceIDIn = ''
        }
        //定向删除事件
        $scope.del = function (type, index, key) {
            var id = $scope.position[type + "Ids"].splice(index, 1),
                node = $scope[type + "Tree"].getNodeByParam("id", id);
            $scope[type + "Tree"].checkNode(node, false, true);
            
            for (var i = 0; i < $scope.position[type + "Ids"].length; i++) {
                node = $scope[type + "Tree"].getNodeByParam("id", $scope.position[type + "Ids"][i]);
                $scope[type + "Tree"].checkNode(node, true, true);
            }
            $scope.add(type, key);
        };

        $(".custom-box").on("click","li", function (e) {
            e.stopPropagation();
            $(this).addClass("current").siblings().removeClass("current")
            // 为第一个子元素li添加current样式
            $(this).find("li").removeClass("current").eq(0).addClass("current");

        });

        $(".custom-box").on("click",".selected-item span", function (e) {
            $(this).parent().remove();
        });

        $(".custom-box").on("click",".addAll", function (e) {
            $(this).parents(".custom-box").find("ul.one >li>.check").each(function(){
                if(!$(this).hasClass("checked")) {
                    $(this).trigger("click");
                }
            })
        });

        $(".custom-box").on("click",".check", function () {
            var $this = $(this),
                $parent,
                $rightBox = $this.parents(".custom-box").find("> .right ul"),
                checked,$ul;
            $this.toggleClass("checked");
            checked = $this.hasClass("checked");
            if(checked) {
                // 选中所有子集
                $this.siblings("ul").find(".check").addClass("checked")
                $ul = $this.parent().parent();
                // 判断是否有父级
                while($ul.siblings(".check").length != 0){
                    // 判断子集是否都被选中
                    if($ul.children().children(".check:not(.checked)").length == 0) {
                        // 所有子集都选中时将本身选中
                        $ul.siblings(".check").addClass("checked");
                    }
                    // 将ul设置为父级
                    $ul = $ul.parent().parent();
                }
            } else {
                // 取消所有子集
                $this.siblings("ul").find(".check").removeClass("checked");
                // 取消所有父级
                $this.parents("ul").siblings(".check").removeClass("checked");
            }
            // 清空右边盒子
            var oneId = $this.attr("parent");
            $rightBox.find(".selected-item[one="+oneId+"]").remove();
            // 找到最顶级li
            $parent = $this.parent().hasClass("one")?$this:$this.parents("ul.one > li");

            $rightBox.append(getTpl($parent));
        });

        function getTpl($li){
            var $check = $li.children(".check");

            if(!$check.hasClass("checked")) {
                // 没有被选中
                var $ul = $check.siblings("ul");
                if($ul.length == 0 ){
                    // 为最后一级时直接返回
                    return ""
                }
                var tpl = '';
                $ul.find(">li").each(function(){
                    tpl += getTpl($(this));
                })
                return tpl;

            } else {
                var ids = [],$subLi = $li.find(">ul>li");
                // 添加id进数组
                ids.push($check.attr("id"))
                // 判断li有没有子集
                if($subLi.length != 0) {
                    // 获取该subLi下的check的id
                    $subLi.each(function () {
                        var $this = $(this)
                        // 保存子集check的id
                        ids.push($this.find(">.check").attr("id"));

                        // 判断subLi还有没有子集
                        if($this.find("li").length != 0){
                            // 保存子集的子集check的id
                            $this.find("li .check").each(function(){
                                ids.push($(this).attr("id"));
                            })
                        }
                    })
                }
                return '<li class="selected-item" id="' + ids.join(",")
                    + '" one="'  + $check.attr("parent")
                    + '">' + $check.find("span").html() + '<span></span></li>'
            }

        }
        //过滤配置
        $scope.config = {
            addAll: function () {
                var $rightBox = $("#areaCustom > .right ul");
                $rightBox.empty();

                $("#areaCustom .check").addClass("checked");
                var tpl = "";
                $("#areaCustom ul.one > li > .check").each(function(){
                    var $check = $(this);
                    tpl += '<li class="selected-item" id="' + $check.attr("id")
                        + '" one="'  + $check.attr("parent")
                        + '">' + $check.find("span").html() + '<span></span></li>'
                })
                $rightBox.append(tpl);
            }
        };

        //==========================================  合约step 2  ==========================================
        $scope.stateList = [{name:'全部状态'},{id:'10',name:'待执行'},{id:'20',name:'执行中'},{id:'30',name:'结束'},{id:'40',name:'售罄'}]
        $scope.platformList = [{name:'全部平台'},{id:'android',name:'Android'},{id:'ios',name:'iOS'}];
        $scope.resList = [{name:'全部资源类型'},{id:'cpc',name:'CPC'},{id:'cpm',name:'CPM'}];
        $scope.filter = {
            self: "1",
            executeState: "10, 20",
            orderID: $scope.orderId
        };
        var buySkuInfo = {
            "adxDealIDs": [],
            "adxIDs": [],
            "adxSpaceIDs": []
        };
        $scope.money = 0;
        if ($scope.step == 2) {
            if ($scope.orderId == "") {
                skuList();
            } else {
                skuList(1, 10);
            }
        }
        //瀑布流
        var masOption = {
            // options
            itemSelector: '.grid-item',
            columnWidth: 340
        };
        //控制合约页面展示
        $scope.dealPage = "list";
        //防止瀑布流没有初始化
        $('.grid').masonry(masOption);
        $scope.$on('ngFinishRender', function(){
            $('.grid').masonry(masOption);
        });
        //资源列表过滤
        $scope.search = function(val) {
            $scope.filter.name = val;
            skuList();
        };
        // 合约资源时间过滤
        $scope.chooseDate = function (start, end) {
            $scope.filter.startDate = start;
            $scope.filter.endDate = end;
            skuList();
        }
        $scope.selectState = function(item) {
            $scope.filter.executeState = item.id;
            skuList();
        };
        $scope.selectPlatform= function(item) {
            $scope.filter.platform = item.id;
            skuList();
        };
        $scope.selectRes = function(item) {
            $scope.filter.chargeType = item.id;
            skuList();
        };
        //查看合约详情
        $scope.dealDetail = function (id, price) {
            $scope.dealPage = "detail";
            getInfo($scope, proxy, id, price);
        };
        //选择合约
        $scope.selectSku = function (item) {
            if (!item.usedDate) {
                item.isSelect = !item.isSelect;
                if (item.isSelect) {
                    $scope.data.SKU.push(item);
                    item.skuIndex = $scope.data.SKU.length - 1;
                } else {
                    $scope.data.SKU.splice(item.skuIndex, 1);
                }
            } else {
                layer.msg("此合约资源无法改变状态。")
            }
        };
        //返回合约列表页
        $scope.backList = function () {
            $scope.dealPage = "list";
        };

        $scope.skuList = [];//控制合约列表
        var dealPage = 1;//控制加载
        $scope.dealListMore = function () {
            if ($scope.countPage > dealPage) {
                dealPage++;
                $scope.loadMoreDeal = false;
            }
            skuList(dealPage);
        };

        //==========================================  step 3  ==========================================
        $scope.dataType = [0, "	品牌名称/贊助信息", "描述信息", "用户评级", "点赞数", "下载数量",
            "价格", "售卖价格", "服务电话", "地址", "描述信息2", "URL", "评论数", "H5","按钮"];
        $scope.adTypes = [0, "banner", "开屏", "插屏", "视频贴片", "原生", "激励视频"];
        $scope.creativeTypes = [0, "单图", "一图三文", "文字链", "视频", "H5", "原生"];
        $scope.interactionTypes = [0, "仅展示", "下载应用", 0 ,"跳转网页"];
        $scope.creative = {};
        //改变广告位类型
        $scope.changSpaceType = function (val) {
            $scope.getModelObj.adType = val;
            getModelList($scope, proxy);
        };
        
        $scope.showInfo = function () {
            layer.open({
                type: 1,
                title: "落地页宏替换",
                content: $('.lp-info-box'),
                area:["672px","534px"]
            })
        }
        //app推广信息
        $scope.appExtension = {
            title: "选择APP",
            changeExtension: function (item) {
                if ($scope.app_num == 'more') {
                    $scope.appExtension.data = {}
                }
                item = angular.copy(item)
                for (var k in item) {
                    $scope.appExtension.data[k] = item[k]
                }
                $scope.appExtension.changeUrl($scope.appExtension.data.marketUrl)
            },
            changeUrl: function (url) {
                if (url) {
                    var sIndex = url.indexOf('id')
                    var eIndex = url.lastIndexOf('?')
                    if (sIndex != -1 && eIndex != -1) {
                        $scope.appExtension.data.itunsID = url.slice(sIndex + 2, eIndex)
                    }
                }
            },
            saveName: function (val) {
                $scope.appExtension.temp_name = $scope.appExtension.title
            },
            changeName: function () {
                if ($scope.appExtension.temp_name != $scope.appExtension.data.name) {
                    if ($scope.app_num == 'more') {
                        $scope.appExtension.data.id = ""
                    }
                }
            },
            data: {},
        }
        //选择模板
        $scope.modelChange = function (model) {
            if (!$scope.isEdit) {
                $scope.currModel = model;
            }
        };
        $('.video-box video')[0].oncanplay = function () {
            this.play();
        }
        $scope.$on('ngFinishRenderVideo', function(){
            // 设置所有video的时间，防止部分浏览器在未播放时为黑屏
            $(".table-box video").each(function(){
                this.oncanplay = function(){
                    this.oncanplay = null;
                    this.currentTime = 4;
                    // this.pause();
                }
            })
        });
        $scope.showVideo = function(src) {
            var video = $('.video-box video')[0];
            if($scope.videoSrc == src) {
                video.currentTime = 0;
                video.pause();
            } else {
                $scope.videoSrc = src;
            }
            layer.open({
                type: 1,
                shade: 0.3,
                closeBtn: 0,
                shadeClose: true,
                area: ['500px', ''], //宽高
                title: false, //不显示标题
                content: $('.video-box'),
                cancel: function(){
                    video.pause()
                }
            })
        }
        $scope.showLibrary = function() {
            layer.open({
                type: 1,
                title: "选择已上传素材",
                content: $('.creative-library'),
                area:["1100px","740px"]
            })
        }
        $scope.isSingleImg = function(item) {
            var m = item.material || [];
            return (m.length == 1 && m[0].image);
        }
        $scope.showImg = function(url) {
            layer.photos({
                photos: {
                    "data": [
                      {
                        "src": url,
                      }
                    ]
                  }
                ,anim: 5
              });
        }
        // 显示明星素材
        $scope.showQua = function() {
            $scope.currModel.starOpen = !$scope.currModel.starOpen;
        }
        $scope.cTypeChange = function (item) {
            $scope.getModelObj.creativeType = item.ID + "";
            $scope.creativeType = item;
            getModelList($scope, proxy);
        };
        //初始化上传按钮
        fileUpload({
            btnId: "upload",
            funcUrl: '0',
            BeforeUpload: function (up, file,cb) {
                checkImg(file, up, $scope,cb);
            },
            FileUploaded: function (info) {
                $scope.$apply(function () {
                    var currUpload = $scope.currUpload,
                        qua = $scope.currModel.qualifications;
                    currUpload.url = info.url;
                    if($scope.currUploadType == "qua") {
                        currUpload.name = "明星资质";
                        if(!qua) {
                            $scope.currModel.qualifications = qua = [];
                        }
                        qua.push(currUpload)
                    } else if($scope.currUploadType == "appIcon") {
                        $scope.appExtension.data.iconURL = info.url;
                    } else {
                        if (currUpload.mims[0].indexOf('video') == -1) {
                            currUpload.width = info.w + "";
                            currUpload.height = info.h + "";
                        }
                        currUpload.mime = info.type;
                        currUpload.size = info.size + "";
                        currUpload.name = info.name;
                    }
                });
            }
        });
       
        //上传素材盒子显示
        $scope.uploadBoxShow = function () {
            $scope.isEdit = false;
            $scope.currModel = "";
            $scope.creative = {};
            if ($stateParams.oType == '1') {
                var filter = {
                    "adInteract": $scope.data.interactionType,
                    "platform":$scope.data.platform == "ios"?"2":"1"
                }
                if ($scope.position.publish == 'all') {
                    filter.adxID = $scope.publishConfig.selectArr.join(",")
                } else if ($scope.position.publish == 'select') {
                    filter.adxAppID = $scope.data.direct.optimizeApp
                } else if ($scope.position.publish == 'new') {
                    filter.adxAppID = $scope.data.direct.newApp
                } else if ($scope.position.publish == 'type') {
                    if($scope.data.chargeMode == "cpc") {
                        filter.adxID = "1"
                    } else {
                        if($scope.typeInOut == 'in') {
                            filter.adxAppType = $scope.data.direct.appTypeIn
                        } else {
                            filter.adxNotAppType = $scope.data.direct.appTypeOut;
                        }
                    }
                } else if ($scope.position.publish == 'industry') {
                    filter.dspSpaceID = $scope.pkgSpaceIds
                } else if ($scope.position.publish == 'crowd') {
                    filter.dspSpaceID = $scope.pkgSpaceIds
                } else if ($scope.position.publish == 'space') {
                    if($scope.position.spaceOutIn == 'in') {
                        filter.dspSpaceID = $scope.position.spaceIds.join(',')
                    } else {
                        filter.dspNotSpaceID = $scope.position.spaceIds.join(',')
                    }
                }
                getFilter($scope, proxy, filter);
            } else {
                getFilter($scope, proxy, {
                    "adxDealID": buySkuInfo.adxDealIDs.join(","),
                    "adxID": buySkuInfo.adxIDs.join(","),
                    "dspSpaceID": buySkuInfo.adxSpaceIDs.join(","),
                    "platform":$scope.data.platform == "ios"?"2":"1"
                });
            }
            if ($scope.app_num == 'more' || $scope.materialList.length == 0) {
                $scope.appExtension.show = true;
            } else {
                $scope.appExtension.show = false;
            }
            $scope.appExtension.title = "选择APP"
            getExtensionList(proxy, $scope);
            if ($scope.app_num == 'more') {
                $scope.appExtension.data = {}
            }
            $scope.creativeBox = true;
        };
        //上传框的隐藏
        $scope.uploadBoxHide = function () {
            // var arr = $scope.extensionTemp
            // for (var i = 0, l = arr.length; i < l; i++) {
            //     if (arr[i].id == $scope.appExtension.data.id) {
            //         $scope.appExtension.changeExtension(arr[i])
            //     }
            // }
            $scope.creativeBox = false;
        };
        //编辑创意
        $scope.creativeEdit = function (m, index) {
            $scope.isEdit = true;
            $scope.currModel = m;
            $scope.currModelIndex = index;
            $scope.creative = {
                name: m.name,
                clickUrl: m.clickUrls ? m.clickUrls.join(",") : "",
                viewUrl: m.viewUrls ? m.viewUrls.join(",") : "",
                landing: m.landingUrl
            };
            //回填推广APP信息
            $scope.appExtension.data = m.advApp;
            if ($stateParams.oType == '1') {
                var filter = {
                    "adInteract": $scope.data.interactionType,
                    "platform":$scope.data.platform == "ios"?"2":"1"
                }
                if ($scope.position.publish == 'all') {
                    filter.adxID = $scope.publishConfig.selectArr.join(",")
                } else if ($scope.position.publish == 'select') {
                    filter.adxAppID = $scope.data.direct.optimizeApp
                } else if ($scope.position.publish == 'new') {
                    filter.adxAppID = $scope.data.direct.newApp
                } else if ($scope.position.publish == 'type') {
                    filter.adxID = "1"
                    // if($scope.typeInOut == 'in') {
                    //     filter.adxAppType = $scope.data.direct.appTypeIn
                    // } else {
                    //     filter.adxNotAppType = $scope.data.direct.appTypeOut;
                    // }
                } else if ($scope.position.publish == 'industry') {
                    filter.dspSpaceID = $scope.pkgSpaceIds
                } else if ($scope.position.publish == 'crowd') {
                    filter.dspSpaceID = $scope.pkgSpaceIds
                } else if ($scope.position.publish == 'space') {
                    if($scope.position.spaceOutIn == 'in') {
                        filter.dspSpaceID = $scope.position.spaceIds.join(',')
                    } else {
                        filter.dspNotSpaceID = $scope.position.spaceIds.join(',')
                    }
                }
                getFilter($scope, proxy, filter);
            } else {
                var dataObj = {
                    "adxDealID": buySkuInfo.adxIDs.join(","),
                    "adxID": buySkuInfo.adxIDs.join(","),
                    "adxSpaceID": buySkuInfo.adxSpaceIDs.join(","),
                    "platform":$scope.data.platform == "ios"?"2":"1",
                };
                getFilter($scope, proxy, dataObj);
            }
            if (index == 0 && $scope.app_num == 'one') {
                $scope.appExtension.show = true
            } else if (index != 0 && $scope.app_num == 'one') {
                $scope.appExtension.show = false
            } else if ($scope.app_num == 'more') {
                $scope.appExtension.show = true
            }
            getExtensionList(proxy, $scope, 'edit');
            // 判断是否存在明星资质
            if(m.qualifications instanceof Array ) {
                $scope.creativeBox = true;
            } else {
                // 根据list获取明星资质信息
                proxy.proxy({
                    url: STATIC_URL.domian+'/dsp/creative/list',
                    data: {
                        'page': "1",
                        'size': "20",
                        'filter': {
                            id: m.id
                        }
                    },
                    success: function(res){
                        m.qualifications = res.data.data[0].qualifications;
                        $scope.creativeBox = true;
                    }
                })
            }
        };
        //上传按钮方法
        $scope.upload = function (m, type) {
            $scope.currUpload = m;
            $scope.currUploadType = type;
            $("#upload").trigger('click');
        };
        //添加创意
        $scope.addCreative = function () {
            $scope.currModel = $scope.currModel ? $scope.currModel : {}
            $scope.currModel.adType = $scope.getModelObj.adType;
            $scope.currModel.creativeType = $scope.getModelObj.creativeType;
            var ms = $scope.currModel.material;
            for (var i = 0, l = ms.length; i < l; i++) {
                if (ms[i].image && !ms[i].image.url) {
                    return layer.msg("请上传图片。");
                } else if (ms[i].text && !ms[i].text.content) {
                    return layer.msg("请输入文本。");
                } else if (ms[i].video && !ms[i].video.url) {
                    return layer.msg("请上传视频。");
                } else if (ms[i].data && !ms[i].data.content) {
                    return layer.msg("请输入"+ $scope.dataType[ms[i].data.type] +"。");
                }
            }
            if ($scope.isEdit) {//编辑创意
                editCreative(proxy, $scope);
            } else { //添加创意
                addCreative(proxy, $scope);
            }
        };
        $scope.starLevel = [{"id": "1", "name": "0.5星"},{"id": "2", "name": "1.0星"},
            {"id": "3", "name": "1.5星"},{"id": "4", "name": "2.0星"},{"id": "5", "name": "2.5星"},{"id": "5", "name": "3.0星"}
            ,{"id": "5", "name": "3.5星"},{"id": "5", "name": "4.0星"},{"id": "5", "name": "4.5星"},{"id": "5", "name": "5.0星"}];
        //查看图片
        $scope.imgShow = function (url) {
            layer.open({
                type: 1,
                title: false,
                closeBtn: 0,
                area: '516px',
                skin: 'layui-layer-nobg', //没有背景色
                shadeClose: true,
                content: '<img style="height: 50%; width: 50%;" src="'+ url +'"></img>'
            });
        };

        $scope.delPic = function (index, type) {
            if(type == "qua") {
                $scope.currModel.qualifications.splice(index,1);
            } else {
                $scope.currModel.material[index][type].url = "";
            }
        };

        $scope.delCreative = function (id, index) {
            deleteCreative($scope, proxy, id, index);
        };
        //==========================================  step 4  ==========================================
        hasCPC(proxy, $scope);//显示或者隐藏CPC出价
        //是否设置利润
        $scope.profit = "false";
        //展示人群包
        $scope.pkgView = ""
        $scope.switchProfit = function(value){
            $scope.profit = value;
        }
        //=========================================   编辑 =============================================
        if ($stateParams.orderId != "") {//编辑

            proxy.proxy({
                url: STATIC_URL.domian + '/dsp/order',
                data: {
                    "id": $stateParams.orderId
                },
                load: true,
                success: function (res) {

                    var direct = res.data.direct;
                    $scope.data = res.data;
                    $scope.activeTitle = $scope.data.activeName;
                    $scope.activeIndustry =   $scope.data.industry;

                    getBrand($scope, proxy);
                    getOsVersion($scope, proxy);
                    getSpace($scope, proxy);
                    getMonitor();
                    
                    // 恢复年龄
                    if(direct.ageIn) {
                        $scope.position.age = "custom";
                        $scope.position.ages = direct.ageIn.split(',');
                    }
                    // 恢复性别定向
                    if(direct.earningIn) {
                        $scope.position.income = "custom";
                        $scope.position.incomes = direct.earningIn.split(',');
                    }
                    // 恢复性别定向
                    if(direct.genderIn) {
                        $scope.position.people = "custom";
                        $scope.position.sex = direct.genderIn;
                    }
                    //恢复小时投放
                    if (direct.deliverTimeIn && direct.deliverTimeIn!='') {
                        $scope.checkArr = direct.deliverTimeIn.split(',')
                    }
                    //恢复设备价格
                    if(direct.devicePrice && direct.devicePrice!=''){
                        $scope.position.dePrice ='custom';
                        $scope.position.dePrices = direct.devicePrice.split(',');
                    }
                    //恢复联网方式
                    if(direct.net && direct.net!=''){
                        $scope.position.net ='custom';
                        $scope.position.nets =direct.net.split(',');
                    }
                    //恢复运营商
                    if(direct.ISP && direct.ISP!=''){
                        $scope.position.ISP ='custom';
                        $scope.position.ISPs = direct.ISP.split(',');
                    }
                    //是否控制订单预算
                    if ($scope.data.orderBudget != "0" && $scope.data.orderBudget != "") {
                        $scope.limit = false;
                    }
                    $scope.data.profit = $scope.data.profit * 100 + "";
                    if ($scope.data.profit != 0) {
                        $scope.profit = "true";
                    }
                    if (!$scope.data.creativeID) {
                        $scope.data.creativeID = [];
                    }
                    if (!$scope.data.SKU) {
                        $scope.data.SKU = [];
                    }
                    if ($scope.data.endTime != "NULL" && $scope.data.endTime != "") {
                        $scope.endTime = false;
                    }

                    $scope.sUnit = $scope.data.speedUnit == "day" ? "天" : "小时";
                    if ($scope.data.controlMode == "0") {
                        $scope.speed = $scope.data.speedUp == "0" ? "匀速" : "加速";
                    }
                    $scope.tUnit = $scope.data.frequencyUnit=="day" ? "天" : "小时";
                    $scope.app_num = $scope.data.singleApp == "true" ? 'one' : 'more'
                    if ($scope.orderType == 'bid') {//竞价
                        if (direct.sourceIn != "") { // 智能优化定向恢复
                            $scope.position.publish = "all";
                            getPublish($scope, proxy, 'edit');
                        } else if(direct.appTypeIn != ""){ // 媒体分类定向恢复
                            $scope.typeInOut = 'in';
                            $scope.position.publish = "type";
                        } else if(direct.appTypeOut != ""){
                            $scope.typeInOut = 'out';
                            $scope.position.publish = "type";
                        } else if(direct.newApp != ""){ // 新品媒体定向恢复
                            $scope.position.publish = "new";
                            getNewMeida($scope, proxy, 'edit')
                        } else if(direct.optimizeApp != ""){ // 精选媒体定向恢复
                            $scope.position.publish = "select";
                            getMedia($scope, proxy, 'edit');
                        } else if (direct.pkgType == '1') {
                            $scope.position.publish = 'industry'
                            $scope.editIndustryPkgId = direct.pkgID
                            $scope.industryPkgId = direct.pkgID
                        } else if (direct.pkgType == '2') {
                            $scope.position.publish = 'crowd'
                            $scope.editCrowdPkgId = direct.pkgID
                            $scope.crowdPkgId = direct.pkgID
                        // } else if (direct.spaceIDIn != '' && direct.pkgType == '0') {
                        } else if (direct.spaceIDIn != '') {
                            $scope.position.publish = 'space'
                        }
                        if(direct.userLocationIn) {
                            switch(direct.locationType) {
                                case "1":
                                    areaType = $scope.position.area = "cityLevel";
                                    break;
                                case "2":
                                    areaType = $scope.position.area = "location";
                                    break;
                            }
                            $scope.$on('ngRepeatFinished', function (ngRepeatFinishedEvent) {
                                var tempArr;
                                // 判断投放区域类型是否相同
                                if (areaType != $scope.position.area) return;
                                if (direct.userLocationIn != "") {
                                    tempArr = direct.userLocationIn.split(",") || [];
                                    tempArr.forEach(function(v){
                                        // 根据id选中对应的check
                                        $("#areaCustom .check[id="+v+"]").addClass("checked");
                                    });
                                    var tpl = "";
                                    $("#areaCustom ul.one > li").each(function(){
                                        tpl += getTpl($(this))
                                    })
                                    $("#areaCustom .right ul").append(tpl);
                                }
                            });
                            $scope.getLocationType()
                        }

                    }
                }
            });
        } else {
            getMonitor();
        }
        //缓存页面状态
        //$(window).keydown(function (e) {
        //    if (e.keyCode == 116) {
        //        sessionStorage.step = $scope.step;
        //    }
        //});
        //  ===============================================================================================
        function skuList(page, size) {
            var page = (page || 1) + "";
            $scope.filter.outIn = $scope.skuIds;
            $scope.filter.chargeType = $scope.data.chargeMode;
            $scope.filter.platform = $scope.data.platform;
            $scope.filter.skuType = $scope.data.type;
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/sku/show/list',
                data: {
                    "size": (size || 10) + "",
                    "page": page,
                    "sort": ["cTime,1"],
                    "filter": $scope.filter,
                },
                load: true,
                success: function(res){
                    if (res.data.data != null) {
                        $('.grid').masonry('destroy');
                        $scope.countPage = Math.ceil(res.data.total/10);
                        if ($scope.countPage > dealPage) {
                            $scope.loadMoreDeal = true;
                        }
                        var tempArr = res.data.data || [];
                        tempArr.forEach(function(sku){
                            var appInfo = {};
                            var temp = [];
                            sku.appDetail = sku.appDetail || [];
                            sku.appDetail.forEach(function(space){
                                var app = appInfo[space.appID];
                                if(!app) {
                                    appInfo[space.appID] = space;
                                    temp.push({
                                        appName: space.appName,
                                        iconUrl: space.iconUrl,
                                        appType: space.appType
                                    })
                                }
                            })
                            sku.appDetail = temp;
                        })
                        if (page > 1) {
                            $scope.skuList = $scope.skuList.concat(tempArr);
                        } else {
                            $scope.skuList = tempArr;
                        }
                    }
                }
            });
        }
        $scope.getLocationType = function(value){
            value = value || $scope.position.area
            $("#areaCustom .selected-item").remove();

            $scope.config.list = $scope.position[value];
            if(!$scope.config.list) {
                proxy.proxy({
                    url: STATIC_URL.domian+'/dsp/location/type',
                    load:true,
                    data: {
                        category: value
                    },
                    success: function(res){
                        $scope.position[value] = $scope.config.list = res.data;
                    }
                })
            }
        }

        // 获得监测站点列表
        function getMonitor() {
            proxy.proxy({
                url: STATIC_URL.domian + "/dsp/monitor/list",
                data: {
                    "filter":{
                        "state":"10"
                    },
                    "sort":[
                        "cTime,1"
                    ],
                    page: "1",
                    size: "9999",
                },
                success: function (res) {
                    var arr = $scope.monitorList = res.data.data,
                        convertCheck = $scope.convertCheck,
                        monitorConvert;
                    // 判断是否为编辑
                    if($scope.orderId != "") {
                        for(var i = 0; i < arr.length; i++) {
                            // 反填监测站点
                            if($scope.data.monitorSite == arr[i].id) {
                                $scope.monitorTitle = arr[i].name;
                                $scope.convertList = arr[i].events;
                                // 反填转化站点
                                if($scope.data.monitorConvert) {
                                    monitorConvert = $scope.data.monitorConvert.split(",")
                                    $scope.convertList.forEach(function(v) {
                                        if(monitorConvert.indexOf(v.id) != -1) {
                                            convertCheck.push(JSON.stringify(v))
                                        }
                                    })
    
                                    $scope.selectconvert(convertCheck)
                                }
                                break;
                            }
                        }
                    }
                }
            })
        }
    });
    //获取广告主利润值
    function getProfit(scope, proxy) {
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/advertiser',
            data: {
                "id": scope.data.advertiserID
            },
            load: true,
            success: function (res) {
                scope.data.profit = res.data.premium * 100;
            }
        })
    }
    //获取单个活动详情
    function getActiveInfo(scope, proxy) {
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/activity',
            data: {
                "id": scope.activeId
            },
            load: true,
            success: function (res) {
                scope.activeTitle = res.data.name;
                scope.activeStartTime= res.data.startTime;
                scope.activeEndTime = res.data.endTime;
                chooseTime(scope);
            }
        })
    }
    //获取素材过滤条件
    function getFilter(scope, proxy, filter) {
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/creative/template/filter',
            data: {
                "filter": filter,
                "size": "-1"
            },
            load: true,
            success: function (res) {
                //素材类型
                if (res.data.adtypes.length != 0) {
                    scope.upCretiveFilter = {
                        "creativeTypes": res.data.creativeTypes,
                        "adtypes": res.data.adtypes
                    };
                    scope.getModelObj = filter || {};
                    if (!scope.isEdit) {
                        scope.getModelObj.adType = scope.upCretiveFilter.adtypes[0].ID + "";
                        scope.creativeName = scope.upCretiveFilter.creativeTypes[0].name;
                        scope.getModelObj.creativeType = scope.upCretiveFilter.creativeTypes[0].ID + "";
                    } else {
                        scope.getModelObj.adType = scope.currModel.adType;
                        scope.creativeName = scope.creativeTypes[scope.currModel.creativeType];
                        scope.getModelObj.creativeType = scope.currModel.creativeType;
                        scope.getModelObj.templateID = scope.currModel.templateID;
                    }
                    var spaces = res.data.spaceIDs, spaceIdArr = [];
                    for (var i = 0; i < spaces.length; i++) {
                        spaceIdArr.push(spaces[i].ID);
                    }
                    scope.getModelObj.dspSpaceID = spaceIdArr.join(",");
                    getModelList(scope, proxy);
                }
            }
        })
    }
    //获取模板列表
    function getModelList(scope, proxy) {
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/creative/template',
            data: {
                "filter": scope.getModelObj,
                "size": "-1",
                "sort": [
                    "cTime,1"
                ]
            },
            load: true,
            success: function (res) {
                scope.modelList = res.data;
                if (!scope.isEdit) {
                    scope.currModel = res.data[0];
                    scope.modelName = scope.currModel ? scope.currModel.name:"";

                } else {
                    scope.modelName = scope.currModel ? scope.currModel.templateName:"";
                }
                publishEstimate(scope, proxy);
            }
        })
    }
    //获取流量来源
    function getPublish(scope, proxy, type) {
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/adx/list',
            data: {
                "filter": {
                    "state": "10"
                },
                "size": "-1",
                "sort": [
                    "cTime,1"
                ]
            },
            load: true,
            success: function (res) {
                scope.publishConfig = scope.publishConfig || {
                    list: res.data.data,
                    selectArr: [],
                    selectNameArr: []
                };

                if (type == "edit") {
                    scope.publishConfig.selectArr = scope.data.direct.sourceIn.split(",");
                }
            }
        })
    }
    //获取设备品牌
    function getBrand(scope, proxy) {
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/telphone/model',
            method: "post",
            data: {},
            load: true,
            success: function (res) {
                var setting = {
                    check: {
                        enable: true
                    },
                    data: {
                        simpleData: {
                            enable: true,
                            idKey: "id",
                            pIdKey: "pID"
                        },
                        key: {
                            children: "sub",
                            name: "alias"
                        }
                    }
                };
                var obj = {
                    id: "0"
                };
                if (scope.data.platform == "ios") {
                    obj.alias = "ios";
                    obj.sub = res.data.ios;
                } else if (scope.data.platform == "android") {
                    obj.alias = "android";
                    obj.sub = res.data.android;
                }
                scope.brandTree = znode("#tree-box", setting, obj);
            }
        })
    }
    //获取设备版本
    function getOsVersion(scope, proxy) {
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/telphone/osVersion',
            method: "post",
            data: {
            },
            load: true,
            success: function (res) {
                var setting = {
                    check: {
                        enable: true
                    },
                    data: {
                        simpleData: {
                            enable: true,
                            idKey: "id",
                            pIdKey: "pId"
                        },
                        key: {
                            children: "sub",
                            name: "name"
                        }
                    }
                };
                if (scope.data.platform == "ios") {
                    scope.versionTree = znode("#version-box", setting, res.data.ios);
                } else if (scope.data.platform == 'android') {
                    scope.versionTree = znode("#version-box", setting, res.data.android);
                }
            }
        })
    }
    //获取广告位
    function getSpace(scope, proxy) {
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/space/tree',
            method: "post",
            data: {
                osType: scope.data.platform
            },
            load: true,
            success: function (res) {
                var setting = {
                    check: {
                        enable: true
                    },
                    data: {
                        simpleData: {
                            enable: true,
                            idKey: "id",
                        },
                        key: {
                            children: "sub",
                            name: "name"
                        }
                    }
                };
                var obj = {
                    id: "0",
                    sub: res.data,
                    open: true
                };
                if (scope.data.platform == "ios") {
                    obj.name = "ios";
                } else if (scope.data.platform == "android") {
                    obj.name = "android";
                }
                scope.spaceTree = znode("#space-box", setting, obj);
            }
        })
    }
    //恢复树形结构
    function editTree(scope, type, ids) {
        var arr = type == "brand" ? ids.split(":") : ids.split(","),
            node;
        for (var i = 0; i < arr.length; i++) {
            if (type != "brand") {
                node = scope[type + "Tree"].getNodeByParam("id", arr[i]);
            } else {
                node = scope[type + "Tree"].getNodeByParam("name", arr[i]);
            }
            node && scope[type + "Tree"].checkNode(node, true, true);
        }
        if (type == "brand")
            scope.add(type, "alias");
        else
            scope.add(type, "name");
    }
    //树形初始化
    function znode(domId, setting ,zNodes) {
        var zTree = $.fn.zTree.init($(domId), setting, zNodes);
        //换位置
        //var openDom = $("span[class*=_open]");
        //var closeDom = $("span[class*=_close]");
        //var openLength = openDom.length;
        //var closeLength = closeDom.length;
        //for (var i = 0; i < openLength; i++) {
        //    changePosition(openDom[i]);
        //}
        //for (var j = 0; j < closeLength; j++) {
        //    changePosition(closeDom[j]);
        //}
        //
        //function changePosition(dom) {
        //    var nextDom = $(dom).next().clone(true);
        //    $(dom).next().remove();
        //    $(dom).parent().prepend(nextDom);
        //}
        return zTree;
    }
    //获取精选媒体
    function getMedia(scope, proxy, type) {
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/adx/app/space',
            data: {
                "filter":{
                    "optimization":"1",
                    "platform": scope.data.platform == "ios" ? '2':'1'
                }
            },
            load: true,
            success: function (res) {
                scope.mediaConfig = scope.mediaConfig || {
                    list: res.data.data,
                    selectArr: [],
                    selectNameArr: []
                };

                if (type == "edit") {
                    scope.mediaConfig.selectArr = scope.data.direct.optimizeApp.split(",");
                }
            }
        })
    }
    //获取新品媒体
    function getNewMeida (scope, proxy, type) {
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/adx/app/space',
            data: {
                "filter":{
                    "newAppCount": "30",
                    "platform": scope.data.platform == "ios" ? '2' : '1'
                }
            },
            load: true,
            success: function (res) {
                scope.newMediaConfig = scope.newMediaConfig || {
                    list: res.data.data,
                    selectArr: [],
                    selectNameArr: []
                };
                if (type == "edit") {
                    scope.newMediaConfig.selectArr = scope.data.direct.newApp.split(",");
                }
            }
        })
    }
    // 行业包
    function industryList(scope, proxy) {
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/industry/package/query',
            data: {
                filter: {
                    os: scope.data.platform == 'ios' ? '2' : '1'
                },
                size: '-1'
            },
            load: true,
            success: function (res) {
                scope.industryPkgList = res.data.data
            }
        })
    }
    // 人群包
    function crowdList(scope, proxy) {
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/people/package/query',
            data: {
                filter: {
                    os: scope.data.platform == 'ios' ? '2' : '1'
                },
                sort: ['tag,1'],
                size: '-1'
            },
            load: true,
            success: function (res) {
                scope.crowdPkgList = res.data.data
            }
        })
    }
    //获取媒体分类
    function getPublishMeidaType(scope, proxy) {
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/adx/app/type',
            data: {},
            load: true,
            success: function (res) {
                scope.mediaTypeList = res.data;
                if(scope.orderId != "") {
                    setTimeout(function(){
                        var tempArr = [];
                        // 回填媒体类型
                        if(scope.data.direct.appTypeIn != ""){
                            if (scope.data.direct.appTypeIn != "") {
                                tempArr = scope.data.direct.appTypeIn.split(",") || [];
                                tempArr.forEach(function(v){
                                    // 根据id选中对应的check
                                    var $check = $("#typeCustom .check[id="+v+"]");
                                    // 触发点击事件
                                    $check.trigger("click");
                                });
                            }
                        } else if(scope.data.direct.appTypeOut != ""){
                            if (scope.data.direct.appTypeOut != "") {
                                tempArr = scope.data.direct.appTypeOut.split(",") || [];
                                tempArr.forEach(function(v){
                                    // 根据id选中对应的check
                                    var $check = $("#typeCustom .check[id="+v+"]");
                                    // 触发点击事件
                                    $check.trigger("click");
                                });
                            }
                        }
                    },1000)
                }
            }
        })
    }
    //获取sku详情
    function getInfo(scope, proxy, id, price){
        var data = {
            'skuID': id
        };
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/sku',
            data: data,
            load:true,
            success: function(res){
                scope.sku = res.data;
                if (price)
                    scope.sku.price = price;
            }
        })
    }
    //添加创意
    function addCreative(proxy, scope) {
        var error = isUrl(scope);
        if (error) {
            return layer.msg(error);
        }
        var data = {
            "name": scope.creative.name,
            "templateID": scope.currModel.templateId,
            "interactionType": scope.data.interactionType,
            "material": scope.currModel.material,
            "landingUrl": scope.creative.landing,
            "viewUrls": scope.creative.viewUrl ? scope.creative.viewUrl.split(" "):[],
            "clickUrls": scope.creative.clickUrl ? scope.creative.clickUrl.split(" ") : [],
            "adType": scope.currModel.adType,
            "creativeType": scope.currModel.creativeType,
            "industry": scope.activeIndustry,
            "qualifications": scope.currModel.qualifications || []
        }
        if (scope.data.interactionType == '2') {
            scope.appExtension.data.platform = scope.data.platform
            scope.appExtension.data.orgID = scope.data.orgID
            scope.appExtension.data.advertiserID = scope.data.advertiserID
            data.advApp = scope.appExtension.data
        }
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/creative/add',
            data: {
                "data": data
            },
            load: true,
            success: function (res) {
                scope.materialList.push(res.data[0]);
                scope.data.creativeID.push(res.data[0].id + "");
                res.data[0].spaceType = scope.getModelObj.adTypeName;
                updateAppInfo(scope, res.data[0])
                //auditState(scope, proxy, [res.data[0].id]);
                scope.creativeBox = false;
            }
        })
    }
    //编辑创意
    function editCreative(proxy, scope) {
        var error = isUrl(scope, 'edit');
        if (error) {
            return layer.msg(error);
        }
        var data = {
            "id": scope.currModel.id,
            "name": scope.creative.name,
            "templateID": scope.currModel.templateID,
            "interactionType": scope.data.interactionType,
            "material": scope.currModel.material,
            "landingUrl": scope.creative.landing,
            "viewUrls": scope.creative.viewUrl ? scope.creative.viewUrl.split(","):[],
            "clickUrls": scope.creative.clickUrl ? scope.creative.clickUrl.split(",") : [],
            "adType": scope.currModel.adType,
            "creativeType": scope.currModel.creativeType,
            "industry": scope.activeIndustry,
            "qualifications": scope.currModel.qualifications || []
        }
        if (scope.data.interactionType == '2') {
            scope.appExtension.data.platform = scope.data.platform
            scope.appExtension.data.orgID = scope.data.orgID
            scope.appExtension.data.advertiserID = scope.data.advertiserID
            data.advApp = scope.appExtension.data
        }
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/creative/modify',
            data: {
                "data": data
            },
            load: true,
            success: function (res) {
                scope.materialList[scope.currModelIndex] = res.data;
                updateAppInfo(scope, res.data)
                scope.creativeBox = false;
                //auditState(scope, proxy, [res.data[0].id], scope.currModelIndex);
            }
        })
    }
    //素材尺寸限制
    function checkImg(file, up, scope,cb) {
        var nFile = file.getNative();
        var reader = new FileReader();
        reader.onload = function() {
            scope.currUpload.md5 = hex_md5(reader.result)
        }
        reader.readAsBinaryString(nFile);
        switch(scope.currUploadType) {
            case "img":
            case "icon":
                var reg = /.(png|jpe?g|gif)$/i,
                    image = new Image();
                // 判断文件类型
                if(!reg.test(file.name)){
                    up.removeFile(file);
                    layer.msg("格式错误，请上传png，jpg，jpeg，gif格式。");
                }
                image.onload= function() {
                    var checkWidth = image.width == scope.currUpload.width,
                        checkHeight = image.height == scope.currUpload.height;
                    if(!checkWidth || !checkHeight) {
                        up.removeFile(file);
                        return layer.msg("图片尺寸不合适，请重新上传(尺寸应为"+ scope.currUpload.width +"x"+ scope.currUpload.height +")");
                    }
                    if (file.size > scope.currUpload.size) {
                        up.removeFile(file);
                        return layer.msg("图片大小不合适，请重新上传(最大限制为"+ Number(scope.currUpload.size / 1024).toFixed(0) + "KB)");
                    }
                    cb && cb();
                };
                image.src = window.URL.createObjectURL(nFile);
            break;
            case "video":
                var url, video;
                // 文件大小判断
                if (file.size > scope.currUpload.size) {
                    up.removeFile(file);
                    layer.msg("视频大小不合适，请重新上传(最大限制为"+ Number(scope.currUpload.size / 1024).toFixed(0) + "KB)");
                    return;
                }
                url = window.URL.createObjectURL(file.getNative());
                video = $(".video_temp").attr("src",url)[0];
                video.oncanplay = function () {
                    video.oncanplay = null;
                    var max = scope.currUpload.maxDuration,
                        min = scope.currUpload.minDuration,
                        duration = Math.round(this.duration);
                    
                    // 判断视频时长
                    if( min <= duration && duration <= max ) {
                        scope.currUpload.duration = duration + "";
                    } else {
                        up.removeFile(file);
                        layer.msg("视频时长不合适，请重新上传(时长应为"+ min +"秒-"+ max +"秒)");
                        return;
                    }
                    // 判断视频长宽
                    if(Math.abs(scope.currUpload.width/this.videoWidth - scope.currUpload.height/this.videoHeight) < 0.01) {
                        scope.currUpload.duration = this.duration.toFixed(0) + "";
                        cb && cb();
                    } else {
                        up.removeFile(file);
                        layer.msg("当前视频尺寸为"+this.videoWidth+"x"+this.videoHeight+"，请重新上传(尺寸比例应接近"+ scope.currUpload.width +"x"+ scope.currUpload.height +",误差不超过10px)");
                    }
                }
            break;
            case "appIcon":
                var reg = /.(png|jpe?g|gif)$/i,
                    image = new Image();
                // 判断文件类型
                if(!reg.test(file.name)){
                    up.removeFile(file);
                    layer.msg("格式错误，请上传png，jpg，jpeg，gif格式。");
                }
                image.onload= function() {
                    if(image.width / image.height != 1) {
                        up.removeFile(file);
                        return layer.msg("图片尺寸尺寸应为1:1");
                    }
                    if (file.size > 50*1024) {
                        up.removeFile(file);
                        return layer.msg("图片大小不合适，请重新上传(最大限制为50KB)");
                    }
                    cb && cb();
                };
                image.src = window.URL.createObjectURL(nFile);
            break;
            case "qua":
                var reg = /.(png|jpe?g|gif)$/i;
                // 判断文件类型
                if(!reg.test(file.name)){
                    up.removeFile(file);
                    layer.msg("格式错误，请上传png，jpg，jpeg，gif格式。");
                } else {
                    cb && cb();
                }
            break;
        }
    }
    //获取订单创意
    function getOrderCreative(scope, proxy, id) {
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/order/creative/list',
            data: {
                "orderID": id
            },
            load: true,
            success: function (res) {
                scope.materialList = res.data;
                if (scope.orderId != "") {
                    for (var i = 0, l = scope.materialList.length; i < l; i++) {
                        scope.data.creativeID.push(scope.materialList[i].id);
                    }
                }
            }
        });
    }
    //编辑订单
    function orderEdit(scope, proxy, id) {
        if (scope.profit == "true") {
            var premium = scope.data.profit / 100;
            if(premium < 0) return layer.msg("利润必须大于等于0！")
            if(premium > scope.premiumMax) return layer.msg("利润设置不能超过"+($scope.premiumMax*100)+"%")
            scope.data.profit = premium + "";
        } else {
            scope.data.profit = "";
        }
        if (scope.data.startTime.indexOf("00:00") == -1) {
            scope.data.startTime += " 00:00:00";
            if (!scope.endTime && scope.data.endTime.replace(/\s/g, "") != "") {
                scope.data.endTime += " 23:59:59";
            }
        }
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/order/modify',
            data: {
                "data": scope.data
            },
            load: true,
            success: function (res) {
                window.location.href = "#/agent/"+ scope.accountType +"/"+ id +"/delivery/order";
            }
        });
    }
    //订单填写验证
    function inputCheck(scope) {
        var data = scope.data,
            error,
            step = scope.step;
        if (step == 1) {
            if (data.activityID == "" || data.activityID == "0") {
                error = "请选择活动。";
                return error;
            }
            if (data.name == "") {
                error = "请输入订单名称。";
                return error;
            }
            if (scope.limit == false) {
                if(data.orderBudget == "") {
                    error = "请输入预算控制。";
                    return error;
                } else if(isNaN(data.orderBudget) || data.orderBudget == "0"){
                    error = "预算为大于0的数字！";
                    return error;
                }
            }
        } else if (step == 2 && scope.orderType == 'bid'){
            var ip = scope.data.direct.ip || "",
                ips = ip.split(",");
            if(ip != "") {
                if (ip.indexOf("，") != -1) {
                    error = "ip定向格式错误！多个ip请使用英文的','！";
                    return error;
                }
                for(var i = 0;i < ips.length; i++) {
                    if( !ips[i].match(/(?=(\b|\D))(((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))(?=(\b|\D))/) ){
                        return "ip格式有误";
                    }
                }
            }
            if (scope.bidActive == 2) {
                if(scope.depotCheck.length > 5) {
                    error = "人群库不能超过5个！";
                    return error;
                }
                if(scope.depotCheck.length == 0) {
                    error = "请选择人群库！";
                    return error;
                }
            } else {
                if (scope.position.age == "custom" && scope.position.ages.length == 0) {
                    error = "请选择年龄定向。";
                    return error;
                }
                if (scope.position.income == "custom" && scope.position.incomes.length == 0) {
                    error = "请选择收入定向。";
                    return error;
                }
            }
            if (scope.position.area != "all" && $("#areaCustom .selected-item").length == 0) {
                error = "请选择投放区域。";
                return error;
            }
            if (scope.position.publish == "all" && scope.publishConfig.selectArr.length == 0) {
                error = "必须选择一个流量来源（全网智能优化）。";
                return error;
            }
            if (scope.position.publish == "space" && scope.position.spaceIds.length == 0) {
                error = "请输入指定广告位。";
                return error;
            }
            if (scope.position.publish == 'industry' && !scope.industryPkgId) {
                error = "请选择行业包。";
                return error;
            }
            if (scope.position.publish == 'crowd' && !scope.crowdPkgId) {
                error = "请选择人群包。";
                return error;
            }
            var medias = scope.mediaConfig.selectArr,
                fLen = 0;
            for (var i = 0; i < medias.length; i++) {
                if (medias[i] != "") {
                    fLen++;
                }
            }
            if (scope.position.publish == "select" && fLen == 0) {
                error = "请选择精选媒体。";
                return error;
            }
            medias = scope.newMediaConfig.selectArr
            fLen = 0;
            for (var i = 0; i < medias.length; i++) {
                if (medias[i] != "") {
                    fLen++;
                }
            }
            if (scope.position.publish == "new" && fLen == 0) {
                error = "请选择新品媒体。";
                return error;
            }
            if (scope.position.publish == "type" && $("#typeCustom .selected-item").length == 0) {
                error = "请选择媒体分类。";
                return error;
            }
            if (scope.position.dePrice != "all" && scope.position.dePrices.length == 0) {
                error = "请选择设备价格。";
                return error;
            }
            if (scope.position.deBrand != "all" && scope.position.brandIds.length == 0) {
                error = "请选择设备品牌。";
                return error;
            }
            if (scope.position.deVersion != "all" && scope.position.versionIds.length == 0) {
                error = "请选择系统版本。";
                return error;
            }
            if (scope.position.net != "all" && scope.position.nets.length == 0) {
                error = "请选择联网方式。";
                return error;
            }
            if (scope.position.ISP != "all" && scope.position.ISPs.length == 0) {
                error = "请选择运营商。";
                return error;
            }

        } else if (step == 2 && scope.orderType == 'deal') {
            if (scope.data.SKU.length == 0) {
                error = "请选择一个合约资源。";
                return error;
            }
        } else if (step == 3) {
            if (scope.materialList.length == 0) {
                error = "请上传一个创意。";
                return error;
            }
        } else if (step == 4 && scope.oType == "pdb") {
            if (data.bidPrice == "") {
                error = "请输入订单出价。";
                return error;
            }
            if (data.bidPrice <= 0) {
                error = "订单出价必须大于0。";
                return error;
            }
            if (data.profit > 100) {
                error = "利润设置不能大于100。";
                return error;
            }
        }
        return error;
    }
    //初始化日历控件
    function chooseTime(scope, type){
        var d = new Date(),
            month = d.getMonth()+ 1,
            today = d.getFullYear()+"-"+(month < 10 ? "0" + month : month)+"-"+ (d.getDate() < 10 ? "0" + d.getDate():d.getDate()),
            sMs = new Date(scope.activeStartTime).getTime(),
            tMs = new Date(today).getTime();

        if (scope.orderId == "" || type == "select") {
            scope.data.startTime = scope.activeStartTime = sMs > tMs ? scope.activeStartTime:today;
            scope.data.endTime = scope.activeEndTime==""?"":scope.activeEndTime;
        }
        scope.isLongTime = scope.activeEndTime=="" ? true:false;
        scope.endTime = scope.activeEndTime=="" ? true:false;
        st = $("#startTime").datetimepicker({
            format: 'yyyy-mm-dd',
            todayHighlight: true,
            minView: 'month',
            autoclose: 'true',
            language: "zh-CN",
            startTime: today,
            endTime: today
        });

        et = $("#endTime").datetimepicker({
            format: 'yyyy-mm-dd',
            todayHighlight: true,
            minView: 'month',
            autoclose: 'true',
            language: "zh-CN",
            startTime: today,
            endTime: today
        });
        st.datetimepicker('setStartDate', scope.activeStartTime);
        et.datetimepicker('setStartDate', scope.activeStartTime);
        if (scope.isLongTime) {
            st.datetimepicker('setEndDate', "2222-10-10");
            et.datetimepicker('setEndDate', "2222-10-10");
        } else {
            st.datetimepicker('setEndDate', scope.activeEndTime);
            et.datetimepicker('setEndDate', scope.activeEndTime);
        }
        st.off('changeDate').on('changeDate', function () {
            scope.data.startTime = st.val();
            et.datetimepicker('setStartDate', st.val());
        });
        et.off('changeDate').on('changeDate', function () {
            scope.data.endTime = et.val();
            st.datetimepicker('setEndDate', et.val());
        });
    }
    //删除素材
    function deleteCreative(scope, proxy, id, index) {
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/order/creative/del',
            data: {
                "orderID": scope.orderId,
                "creativeID": id
            },
            load: true,
            success: function (res) {
                scope.materialList.splice(index, 1);
                scope.data.creativeID.splice(index, 1);
            }
        })
    }
    //流量预估
    function publishEstimate(scope, proxy) {
        var tIds = [];
        for (var i = 0; i < scope.modelList.length; i++) {
            tIds.push(scope.modelList[i].templateId);
        }
        if (tIds.length != 0) {
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/order/template/flow',
                data: {
                    templateID: tIds
                },
                load: true,
                success: function (res) {
                    scope.estimate = res.data;
                    scope.currEstimate = scope.estimate[scope.currModel.templateId];
                }
            })
        }
    }
    //控制CPC出价
    function hasCPC(proxy, scope) {
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/sys/parameter/query',
            data: {
                "filter":{"feature":"dsp.feature.advertiser.order.cpc.allow"}
            },
            success: function(res){
                scope.hasCPC = res.data[0].value;
            }
        })
    }
    // ip定向
    function hasIP(proxy, scope) {

        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/sys/parameter/query',
            data: {
                "filter":{"feature":"dsp.feature.advertiser.order.ip.direct"}
            },
            success: function(res){
                scope.hasIP = res.data[0].value;
            }
        })
    }
    // 控制CPC/CPM最高价格
    function getPriceMax(proxy, scope) {
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/sys/parameter/query',
            data: {
                "filter":{"feature":"dsp.feature.advertiser.order.cpc.maxvalue"}
            },
            success: function(res){
                scope.cpcMax = res.data[0].value*1 || 99;
            }
        })
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/sys/parameter/query',
            data: {
                "filter":{"feature":"dsp.feature.advertiser.order.cpm.maxvalue"}
            },
            success: function(res){
                scope.cpmMax = res.data[0].value*1 || 999;
            }
        })
    }
    //url判断
    function isUrl(scope, type) {
        //var urlReg = /^((ht|f)tps?):\/\/[\w\-]+(\.[\w\-]+)+([\w\-\.,@?^=%\{\}&:\/~\+#]*[\w\-\@?^=%\{\}&\/~\+#])?$/,
        var urlReg = /^((ht|f)tps?):\/\//,
            error, vUrls = scope.creative.viewUrl ? scope.creative.viewUrl.split(" "):[],
            cUrls = scope.creative.clickUrl ? scope.creative.clickUrl.split(" "):[];
        if (!scope.creative.name) {
            return "创意名称不能为空。";
        }
        if (!scope.creative.landing && (scope.data.interactionType == '2' || scope.data.interactionType == '4' || scope.orderType == 'deal')) {
            return "落地页地址不能为空。";
        }
        if (scope.creative.landing && !urlReg.test(scope.creative.landing) && (scope.data.interactionType == '2' || scope.data.interactionType == '4' || scope.orderType == 'deal')) {
            return "落地页地址不合法。";
        }
        var condition = scope.data.interactionType == '2' && (scope.materialList.length == 0 && scope.app_num == 'one')
        // if (condition || type) {
        if (condition) {
            if (!scope.appExtension.data.name) {
                return "应用名称不能为空。"
            } else if (scope.data.platform == 'ios' && !scope.appExtension.data.marketUrl) {
                return "APPStore URL不能为空。"
            } else if (scope.data.platform == 'android' && !scope.appExtension.data.packageName) {
                return "APK包名不能为空。"
            } else if (scope.data.platform == 'android' && !scope.appExtension.data.downloadUrl) {
                return "下载URL不能为空。"
            } else if (!scope.appExtension.data.version) {
                return "版本不能为空。"
            } else if (!scope.appExtension.data.description) {
                return "描述不能为空。"
            } else if (scope.data.platform == 'ios' && scope.appExtension.data.marketUrl) {
                if (scope.appExtension.data.marketUrl.indexOf('apple.com') == -1) {
                    return "请输入正确的appStore地址。"
                }
                if(!scope.appExtension.data.itunsID) {
                    return "监测不到itunsID！";
                }
            } else if (!scope.appExtension.data.iconURL) {
                return "请上传Appicon。"
            } 
        }

        for (var i = 0, l = cUrls.length; i < l; i++) {
            if (!urlReg.test(cUrls[i])) {
                error = "点击监测不合法(多个地址以空格分割，"+ cUrls[i] +" 这个url不合法)";
                break;
            }
        }
        if (error) {
            return error;
        }

        for (var i = 0, l = vUrls.length; i < l; i++) {
            if (!urlReg.test(vUrls[i])) {
                error = "曝光监测不合法(多个地址以空格分割，"+ vUrls[i] +" 这个url不合法)";
                break;
            }
        }
        if (error) {
            return error;
        }
    }
    // 获得最大溢价值
    function getPremiumMax (proxy,$scope) {
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/sys/parameter/query',
            load: true,
            token: localStorage.agbToken,
            data: {
                "filter":{"feature":"dsp.feature.agency.advertiser.profix.maxvalue"}
            },
            success: function(res){
                $scope.premiumMax = res.data[0].value*1 || 0.6;
            }
        })
    }
    //获取已有APP推广信息
    function getExtensionList (proxy, scope, type) {
        var check = scope.materialList.length > 0 && scope.data.interactionType == '2'
        if (check) {
            var arr = scope.materialList
            var res = []
            for (var i = 0, l = scope.materialList.length; i < l; i++) {
                var flag = true
                for (var k = 0; k < res.length; k++) {
                    if (res[k].name == scope.materialList[i].advApp.name) {
                        flag = false
                    }
                }
                if (flag && scope.materialList[i].advApp) {
                    res.push(angular.copy(scope.materialList[i].advApp))
                }
            }
            var editArr = scope.appExtension.extensionList = res
            if (scope.app_num == 'one') {
                scope.appExtension.data = res[0]
            }
            scope.extensionTemp = []
            for (var i = 0, l = res.length; i < l; i++) {
                scope.extensionTemp.push(JSON.parse(JSON.stringify(res[i])))
            }
            if (type) {
                for (var i = 0, l = editArr.length; i < l; i++) {
                    if (scope.appExtension.data.id == editArr[i].id) {
                        scope.appExtension.title = editArr[i].name
                        scope.appExtension.changeExtension(editArr[i])
                    }
                }
            }
        }
        // proxy.proxy({
        //     url: STATIC_URL.domian+'/dsp/order/adver/app/list',
        //     load: true,
        //     data: {
        //         filter: {
        //             platform: scope.data.platform
        //         }
        //     },
        //     success: function(res){
        //         var arr = scope.appExtension.extensionList = res.data
        //         if (type) {
        //             for (var i = 0, l = arr.length; i < l; i++) {
        //                 if (scope.appExtension.data.id == arr[i].id) {
        //                     scope.appExtension.title = arr[i].name
        //                 }
        //             }
        //         }
        //     }
        // })
    }
    //更新创建订单时创意列表推广APP信息
    function updateAppInfo(scope, item) {
        if (scope.data.interactionType == '2') {
            var arr = scope.materialList
            for (var i = 0, l = arr.length; i < l; i++) {
                if (arr[i].advApp.id == item.advApp.id) {
                    arr[i].advApp = item.advApp
                }
            }
        }
    }
})();

//日历控件汉化
(function($){
    $.fn.datetimepicker.dates['zh-CN'] = {
        days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
        daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
        daysMin:  ["日", "一", "二", "三", "四", "五", "六", "日"],
        months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
        monthsShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
        today: "今天",
        suffix: [],
        meridiem: ["上午", "下午"]
    };
}(jQuery));